import 'dart:io';
import 'package:google_mlkit_text_recognition/google_mlkit_text_recognition.dart';
import '../models/business_card.dart';

class OCRService {
  static final OCRService _instance = OCRService._internal();
  factory OCRService() => _instance;
  OCRService._internal();

  final TextRecognizer _textRecognizer = TextRecognizer();

  // 从图片中识别文字
  Future<String> recognizeTextFromImage(String imagePath) async {
    try {
      final inputImage = InputImage.fromFilePath(imagePath);
      final RecognizedText recognizedText = await _textRecognizer.processImage(inputImage);
      
      String fullText = '';
      for (TextBlock block in recognizedText.blocks) {
        for (TextLine line in block.lines) {
          fullText += line.text + '\n';
        }
      }
      
      return fullText.trim();
    } catch (e) {
      print('OCR识别错误: $e');
      return '';
    }
  }

  // 从识别的文字中提取名片信息
  Future<BusinessCard?> extractBusinessCardInfo(String imagePath, String recognizedText) async {
    try {
      final lines = recognizedText.split('\n').where((line) => line.trim().isNotEmpty).toList();
      
      String name = '';
      String company = '';
      String position = '';
      String phone = '';
      String email = '';
      String address = '';
      String website = '';
      String notes = '';

      // 提取姓名（通常是第一行或包含中文的行）
      for (String line in lines) {
        if (isChineseName(line.trim())) {
          name = line.trim();
          break;
        }
      }

      // 提取电话号码
      for (String line in lines) {
        String phoneNumber = extractPhoneNumber(line);
        if (phoneNumber.isNotEmpty) {
          phone = phoneNumber;
          break;
        }
      }

      // 提取电子邮件
      for (String line in lines) {
        String emailAddress = extractEmail(line);
        if (emailAddress.isNotEmpty) {
          email = emailAddress;
          break;
        }
      }

      // 提取网站
      for (String line in lines) {
        String webUrl = extractWebsite(line);
        if (webUrl.isNotEmpty) {
          website = webUrl;
          break;
        }
      }

      // 提取公司名称（通常包含"公司"、"有限"、"集团"等关键词）
      for (String line in lines) {
        if (isCompanyName(line.trim())) {
          company = line.trim();
          break;
        }
      }

      // 提取职位（通常包含"经理"、"总监"、"主任"等关键词）
      for (String line in lines) {
        if (isPosition(line.trim())) {
          position = line.trim();
          break;
        }
      }

      // 提取地址（通常包含"路"、"街"、"区"等关键词）
      for (String line in lines) {
        if (isAddress(line.trim())) {
          address = line.trim();
          break;
        }
      }

      // 如果没有提取到基本信息，返回null
      if (name.isEmpty && company.isEmpty && phone.isEmpty && email.isEmpty) {
        return null;
      }

      return BusinessCard(
        name: name,
        company: company,
        position: position,
        phone: phone,
        email: email,
        address: address,
        website: website,
        imagePath: imagePath,
        createdAt: DateTime.now(),
        updatedAt: DateTime.now(),
        notes: notes,
      );
    } catch (e) {
      print('提取名片信息错误: $e');
      return null;
    }
  }

  // 检查是否为中文姓名
  bool isChineseName(String text) {
    if (text.length < 2 || text.length > 4) return false;
    return text.runes.every((rune) => rune >= 0x4E00 && rune <= 0x9FFF);
  }

  // 检查是否为公司名称
  bool isCompanyName(String text) {
    final companyKeywords = ['公司', '有限', '集團', '企業', '科技', '貿易', '實業', '投資', '發展', '建設'];
    return companyKeywords.any((keyword) => text.contains(keyword));
  }

  // 检查是否为职位
  bool isPosition(String text) {
    final positionKeywords = ['經理', '總監', '主任', '主管', '部長', '科長', '助理', '專員', '工程師', '顧問', '總裁', '董事長', '總經理'];
    return positionKeywords.any((keyword) => text.contains(keyword));
  }

  // 检查是否为地址
  bool isAddress(String text) {
    final addressKeywords = ['路', '街', '區', '市', '省', '縣', '鎮', '村', '號', '樓', '層', '室'];
    return addressKeywords.any((keyword) => text.contains(keyword));
  }

  // 提取电话号码
  String extractPhoneNumber(String text) {
    final phoneRegex = RegExp(r'(\+?86)?[-\s]?1[3-9]\d{9}|(\+?86)?[-\s]?\d{3,4}[-\s]?\d{7,8}');
    final match = phoneRegex.firstMatch(text);
    return match?.group(0)?.replaceAll(RegExp(r'[-\s]'), '') ?? '';
  }

  // 提取电子邮件
  String extractEmail(String text) {
    final emailRegex = RegExp(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b');
    final match = emailRegex.firstMatch(text);
    return match?.group(0) ?? '';
  }

  // 提取网站
  String extractWebsite(String text) {
    final websiteRegex = RegExp(r'https?://[^\s]+|www\.[^\s]+');
    final match = websiteRegex.firstMatch(text);
    return match?.group(0) ?? '';
  }

  // 释放资源
  Future<void> dispose() async {
    await _textRecognizer.close();
  }
}
